package cn.asiawu.springboot.controller;

import cn.asiawu.springboot.entity.Files;
import cn.asiawu.springboot.mapper.FileMapper;
import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

//文件上传接口
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private FileMapper fileMapper;
    @Value("${files.upload.path}")
    private String uploadPath;
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize()/1024;//kb
        //上传至磁盘
        File uploadFile=new File(uploadPath);
        //文件夹不存在则创建
        if (!uploadFile.exists())
            uploadFile.mkdirs();
        //保证存储文件名的唯一性
        String time = String.valueOf(System.currentTimeMillis());
        String storedFilename=time+originalFilename;
        String url="www.asiawu.cn:9090/file/"+storedFilename;
        File storedFile=new File(uploadPath+storedFilename);
        //存到服务器
        file.transferTo(storedFile);
        //存到数据库
        Files saveFile=new Files(0,originalFilename,size,url,false);
        fileMapper.insert(saveFile);
        return url;
    }

    //获取文件
    @GetMapping("/{storedFilename}")
    public void download(@PathVariable String storedFilename, HttpServletResponse response) throws IOException {
        // 根据存储文件名获取文件
        File uploadFile = new File(uploadPath + storedFilename);
        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(storedFilename, "UTF-8"));
        response.setContentType("application/octet-stream");
        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}
